package com.kedll.homegoods.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.homegoods.login.ApiUtil;
import com.homegoods.login.R;
import com.homegoods.login.evnet.LoginSucEvent;
import com.homegoods.login.model.ExternalUserModel;
import com.homegoods.login.model.UserProxy;
import com.homegoods.resource.HomeGoodsApp;
import com.kedll.library.KBaseApplication;
import com.kedll.library.contants.Consts;
import com.kedll.library.util.RxBus;
import com.kedll.library.util.SharePreUtils;
import com.kedll.library.util.SystemUtils;
import com.kedll.library.util.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.functions.Consumer;

/**
 * 微信回调类
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI mWXApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.entry);
        mWXApi = WXAPIFactory.createWXAPI(this, Consts.wxAppId, false);
        try {
            mWXApi.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mWXApi.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    /**
     * ERR_OK = 0(用户同意) ERR_AUTH_DENIED = -4（用户拒绝授权） ERR_USER_CANCEL = -2（用户取消）
     *
     * @param baseResp
     */
    @Override
    public void onResp(BaseResp baseResp) {
        if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
            SendAuth.Resp resp = (SendAuth.Resp) baseResp;
            ApiUtil.weChatLogin(resp.code, new Consumer<ExternalUserModel>() {
                @Override
                public void accept(ExternalUserModel e) throws Exception {
                    ApiUtil.tokenGetUserInfo(e.getToken(), e.getSid(), userModel -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("dtype", "Android");
                        map.put("dwsinf", SystemUtils.getManufacture());
                        map.put("otype", SystemUtils.getOSVersion());
                        map.put("dtoken", SystemUtils.getDeviceModel());
                        map.put("appname", "安卓端" + SystemUtils.getMyVersionCode());
                        map.put("marker", "");
                        //首次登录成功后上传设备信息
                        ApiUtil.postDeviceInfo(userModel.getToken(), map, s -> {    //modify shibo.zheng
                            ToastUtil.showToast(R.string.login_suc);
                            //保存用户数据
                            UserProxy.getInstance().saveClientUser(userModel);
                            SharePreUtils.addUser(KBaseApplication.getInstance(), userModel.getMPhone());
                            HomeGoodsApp.setToken(userModel.getToken());    //modify shibo.zheng
                            RxBus.getDefault().post(new LoginSucEvent());
                            WXEntryActivity.this.finish();
                        }, throwable -> {
                        });
                    }, throwable -> {
                    });
                }
            }, throwable -> {
            });
        } else {
            finish();

        }
    }


}
